package com.cby.code.base;

import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.cby.code.util.R;
import com.cby.code.util.ResourcesUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * Description:HykbBaseDialogFragment
 *
 * @author 陈宝阳
 * @create 2020/8/6 10:11
 */
public abstract class BaseDialogFragment extends DialogFragment {

    protected SimpleViewHolder viewHolder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UIStackManager.getInstance().addFragment(this.getTag(), this);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.BaseDialogTheme);
        parseArgs();

        initFontScale();
    }

    protected void initFontScale() {
        Resources resources = super.getResources();
        Configuration newConfig = resources.getConfiguration();
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();

        if (newConfig.fontScale != 1) {
            newConfig.fontScale = 1;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                Context configurationContext = getActivity().createConfigurationContext(newConfig);
                resources = configurationContext.getResources();
                displayMetrics.scaledDensity = displayMetrics.density * newConfig.fontScale;
            }
            resources.updateConfiguration(newConfig, displayMetrics);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null) {
            getDialog().getWindow()
                    .setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
            getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                    | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            setSystemUi();
            getDialog().setCanceledOnTouchOutside(false);
            getDialog().setCancelable(false);
            getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        //拦截返回键事件
                        return isInterceptBackEvent();
                    }
                    return false;
                }
            });
        }
    }

    protected boolean isInterceptBackEvent() {
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(
                ResourcesUtils.getLayoutId(getActivity(), getLayoutName()), container);
        viewHolder = new SimpleViewHolder(view);
        initView(view);
        setContent();
        initListener();
        return view;
    }

    protected abstract void parseArgs();

    protected abstract String getLayoutName();

    protected abstract void initView(View view);

    protected abstract void setContent();

    protected abstract void initListener();

    protected void setSystemUi() {
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                //布局位于状态栏下方
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                //全屏
                View.SYSTEM_UI_FLAG_FULLSCREEN |
                //隐藏导航栏
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        uiOptions |= 0x00001000;
        getDialog().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
    }

    protected int getId(String resName) {
        return ResourcesUtils.getId(getActivity(), resName);
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        try {
            Class c = Class.forName("android.app.DialogFragment");
            Constructor con = c.getConstructor();
            Object obj = con.newInstance();
            Field dismissed = c.getDeclaredField("mDismissed");
            dismissed.setAccessible(true);
            dismissed.set(obj, false);
            Field shownByMe = c.getDeclaredField("mShownByMe");
            shownByMe.setAccessible(true);
            shownByMe.set(obj, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Fragment fragment = manager.findFragmentByTag(tag);
        FragmentTransaction ft = manager.beginTransaction();
        if(fragment != null && fragment.isAdded()) {
            ft.show(fragment);
        } else {
            ft.add(this, tag);
        }
        ft.commitAllowingStateLoss();
    }

    @Override
    public void dismiss() {
        dismissAllowingStateLoss();
    }

    @Override
    public void onDestroy() {
        UIStackManager.getInstance().removeFragment(this.getTag());
        super.onDestroy();
    }
}
